import React, { Component } from 'react'
// import axios from 'axios'
import 'whatwg-fetch'

export default class App extends Component {

  state = {
    repoName: '',
    repoUrl: ''
  }

  componentDidMount() {
    const url = 'https://api.github.com/search/repositories1?q=r&sort=stars';
    // 1. 发送 ajax 请求
    /* axios.get(url)
      .then((response) => {
        console.log(response);
        const result = response.data;
        this.setState({
          repoName: result.items[0].name,
          repoUrl: result.items[0].html_url
        })
      })
      .catch((err) => {
        console.log(err)
      }) */

    // 2.发送 fetch 请求
    window.fetch(url)
      .then( (response)=> {
        // debugger
        if (response.ok) {
          return response.json()
        } else {
          throw new Error('失败')
        }
        
      })
      .then ((result)=>{
        this.setState({
          repoName: result.items[0].name,
          repoUrl: result.items[0].html_url
        })
      })
      .catch((error)=>{
        alert('错误')
        console.log(error)
      })
  }
  render() {
    const { repoName, repoUrl } = this.state
    if (repoName) {
      return <div>最受欢迎的库， <a href={repoUrl} target="blank">{repoName}</a></div>
    } else {
      return <div>LOADING。。。。。</div>
    }

  }
}
